package com.kaluli.project.service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.transaction.Transactional;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.kaluli.project.domain.entity.CpsUserVO;
import com.kaluli.project.domain.entity.CpsVO;
import com.kaluli.project.domain.entity.KllHupuUserVo;
import com.kaluli.project.domain.entity.KllOrderDataVo;
import com.kaluli.project.domain.entity.KllUserDataVo;
import com.kaluli.project.domain.entity.KllUserFormVo;
import com.kaluli.project.domain.repository.KllCpsRepository;
import com.kaluli.project.domain.repository.KllDataRepository;
import com.kaluli.project.domain.repository.KllHupuUserRepository;
import com.kaluli.project.domain.repository.KllOrderRepository;
import com.kaluli.project.domain.repository.KllUserDataRepository;
import com.kaluli.project.utils.DateUtil;

@Service
@Configuration
@Transactional
public class KllDataService extends CommonService {

	@Autowired
	private KllDataRepository kllDataRepository;
	
	@Autowired
	private KllOrderRepository kllOrderRepository;

	@Autowired
	private SimpleDatasheetService simpleDatasheetService;
	
	@Autowired
	private SimpleOrdersheetService simpleOrdersheetService;
	
	@Autowired
	private KllUserDataRepository userDataRepository;
	
	@Autowired
	private KllHupuUserRepository hupuUserRepository;
	
	@Autowired
	private KllCpsRepository kllCpsRepository;
	
	
	
	public List<CpsUserVO> findByCps() {
		List<CpsUserVO> cpsList = new ArrayList<>();
		List<CpsVO> list = kllCpsRepository.findCpsUser();
		
		
		List<KllUserFormVo> user = userDataRepository.findhupuAppUser();
		
		List<CpsVO> register = kllCpsRepository.findCpsLoginUser();
		int count = 0;//hupuapp 用户数
		if(user !=null && user.size()>0){
			KllUserFormVo vo = user.get(0);
			count = vo.getCount();
		}
		if(list == null ){
			return null;
		}
		
		for(CpsVO v:list){
			CpsUserVO cpsVo = new CpsUserVO();
			cpsVo.setCount(v.getCount());
			cpsVo.setDate(DateUtil.OneWeekStr()+"-"+DateUtil.getCurrentDay());
			
			cpsVo.setPrice(v.getPrice());
			cpsVo.setUnionId(v.getUnionId());
			cpsList.add(cpsVo);
		}
		
		
		for(CpsVO re:register){
			for(CpsUserVO u:cpsList){
				if(u.getCount().equals("0")){
					u.setPrice("0");
				}
				if(re.getUnionId().equals(u.getUnionId())){
					
					if(u.getUnionId().equals("hupuappmore")){
						u.setUcnt(Integer.toString(count));
					}else{
						u.setUcnt(re.getCount());
					}
				}
			}
		}
		
		return cpsList;

	}

	/**
	 * 每天发送注册用户信息
	 * 
	 * @param dateTime
	 */
//	@Scheduled(cron = "${nsapi.send.exmail}")
	public void findByTime() {
		Date date = DateUtil.beforeOneDay();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		String dateTime = df.format(date);
		List<KllUserDataVo> data = kllDataRepository.findByTime(dateTime);
		if (data != null && data.size() > 0) {
			try {
				simpleDatasheetService.sendEmailByTime(data);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

	}
	
	
	/**
	 * 每周发送快递统计时间表
	 * 
	 * @param dateTime
	 * @throws Exception 
	 */
	@Scheduled(cron = "${nsapi.send.order}")
	public void findByWeek() throws Exception {
		Date date = DateUtil.beforeOneWeek();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		String dateTime = df.format(date);
		List<KllOrderDataVo> data = kllOrderRepository.findByWeek(dateTime);
		if (data != null && data.size() > 0) {
			simpleOrdersheetService.sendEmailByTime(data);

		}

	}
	
	
	/**
	 * 每周发送快递统计时间表
	 * 
	 * @param dateTime
	 */
	/*
	public void findByData(String type) {
		Date date = DateUtil.beforeOneWeek();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		String dateTime = df.format(date);
		List<KllOrderDataVo> data = kllOrderRepository.findByData(type);
		if (data != null && data.size() > 0) {
			try {
				simpleOrdersheetService.sendEmailByTime(data);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

	}*/
	
	/**
	 * 用户数据日报
	 * @return
	 * @throws Exception
	 */
	public Map findUserData() throws Exception{
		//用户表中说有用户数量
		int allCnt =0;
		List<KllUserFormVo> hupu = userDataRepository.findUserByHupu("all");
		List<KllUserFormVo> kaluli = userDataRepository.findUserByKaluli("all");
		if(hupu != null && hupu.size()>0){
			allCnt += hupu.get(0).getCount();
		}
		if(kaluli != null && kaluli.size()>0){
			allCnt += kaluli.get(0).getCount();
		}
		
		//今天访问过网站的用户数
		int loginCnt=0;
		List<KllUserFormVo> hupuLogin = userDataRepository.findUserByHupu("lastlogin");
		List<KllUserFormVo> kaluliLogin = userDataRepository.findUserByKaluli("lastlogin");
		if(hupuLogin != null && hupuLogin.size()>0){
			loginCnt += hupuLogin.get(0).getCount();
		}
		if(kaluliLogin != null && kaluliLogin.size()>0){
			loginCnt += kaluliLogin.get(0).getCount();
		}
		//购物次数》3的用户数
		int loyalCnt=0;
		List<KllUserFormVo> loyal = userDataRepository.findUserByLoyal();
		if(loyal != null && loyal.size()>0){
			loyalCnt = loyal.get(0).getCount();
		}
		
		//今日新增的用户数
		int todayCnt=0;
		List<KllHupuUserVo> hupuToday = hupuUserRepository.findHupuUserByToday("today");
		int index =0;//hupu当天实际新增用户
		int payCnt=0;//hupu当天实际新增用户 里面付款的用户
		for(KllHupuUserVo vo :hupuToday){
			List<KllUserFormVo> list = userDataRepository.deleteUserByOther(vo.getHupuUid(),"today");
			if(list != null && list.size()>0){
				
			}else{
				index ++;
				if(vo.getPayTime() != null){
					payCnt ++;
				}
			}
		}
		List<KllUserFormVo> kaluliToday = userDataRepository.findUserByKaluli("todayadd");
		if(hupuToday != null && hupuToday.size()>0){
			todayCnt += index;
		}
		if(kaluliToday != null && kaluliToday.size()>0){
			todayCnt += kaluliToday.get(0).getCount();
		}
		//新用户中当日支付成功的用户数
		//payCnt
		
		//3个月内没有访问过网站的用户总数
		int lostCnt=0;
		List<KllUserFormVo> hupulost = userDataRepository.findUserByHupu("lost");
		List<KllUserFormVo> kalulilost = userDataRepository.findUserByKaluli("lost");
		if(hupulost != null && hupulost.size()>0){
			lostCnt += hupulost.get(0).getCount();
		}
		if(kalulilost != null && kalulilost.size()>0){
			lostCnt += kalulilost.get(0).getCount();
		}
		//当日新增的流失用户数
		int losdayCnt=0;
		List<KllUserFormVo> hupuLosday = userDataRepository.findUserByHupu("lostToday");
		List<KllUserFormVo> kaluliLosday = userDataRepository.findUserByKaluli("lostToday");
		if(hupuLosday != null && hupuLosday.size()>0){
			losdayCnt += hupuLosday.get(0).getCount();
		}
		if(kaluliLosday != null && kaluliLosday.size()>0){
			losdayCnt += kaluliLosday.get(0).getCount();
		}
		//用户流失率
		BigDecimal lost = new BigDecimal(0);
		if(todayCnt == 0){
			
		}else{
			
			BigDecimal losday = new BigDecimal(losdayCnt);
			BigDecimal today = new BigDecimal(todayCnt);
		    lost = losday.divide(today, 2, BigDecimal.ROUND_HALF_UP);
		}
		
		//下单人数
		int orderCnt =0;
		List<KllUserFormVo> order = userDataRepository.findUserByOrder("all");
		if(order != null && order.size()>0){
			orderCnt += order.get(0).getCount();
		}
		
		
		//支付笔数
		int orderPayCnt=0;
		List<KllUserFormVo> orderPay = userDataRepository.findUserByOrder("pay");
		if(orderPay != null && orderPay.size()>0){
			orderPayCnt += orderPay.get(0).getCount();
		}
		
		//购物车当日下单成功人数
		int shopCnt = 0;
		List<KllUserFormVo> shop = userDataRepository.findShoppingOrder();
		if(shop != null && shop.size()>0){
			shopCnt = shop.get(0).getCount();
		}
		
		//当日立即购买成功人数
		int buyNowCnt = 0;
		List<KllUserFormVo> buyNow = userDataRepository.findOrderBuyNow();
		if(buyNow != null && buyNow.size()>0){
			buyNowCnt = buyNow.get(0).getCount();
		}
		
		
		Map map = new HashMap<>();
		map.put("date", DateUtil.getCurrentDay());
		map.put("allCnt", allCnt);
//		map.put("loginCnt", loginCnt);
		map.put("loyalCnt", loyalCnt);
		map.put("todayCnt", todayCnt);
		map.put("payCnt", payCnt);
//		map.put("lostCnt", lostCnt);
//		map.put("losdayCnt", losdayCnt);
//		map.put("lost", lost);
//		map.put("orderCnt", orderCnt);
//		map.put("orderPayCnt", orderPayCnt);
		
		map.put("shopCnt", shopCnt);
		map.put("buyNowCnt", buyNowCnt);
		
		return map;
	}
	
	
	/**
	 * 用户数据周报
	 * @return
	 * @throws Exception
	 */
	public Map findUserDataByWeek(String source) throws Exception{
		
		
		
		//90天复购率
		int buyFour =0;
		int reBuyFour=0;
		int reBuyone =0;
		int reBuyTwo =0;
		int reBuyThree =0;
		
		List<KllUserFormVo> fourList = userDataRepository.findOrderByWeek("90",source);
		for(KllUserFormVo vo:fourList){
			List<KllHupuUserVo> user = hupuUserRepository.findOrderByUid(vo.getId().toString());
			if(user !=null && user.size()>0){
				String userName = "";
				for(KllHupuUserVo hu:user){
					Date date = hu.getPayTime();
					int i = DateUtil.intervalDays(new Date(), date);
					if(i>=97){
						break;
					}else if(i<97 && i>=90){
						//分母
						if(StringUtils.isNotBlank(userName)){
							if(userName.equals(hu.getId().toString())){
								continue;
							}
						}
						buyFour++;
					}
					if(i<90){
						//这里统计复购用户数
						if(StringUtils.isNotBlank(userName)){
							if(userName.equals(hu.getId().toString())){
								continue;
							}
						}
						reBuyFour++;
					}
					if(i<30){
						//这里统计复购用户数
						if(StringUtils.isNotBlank(userName)){
							if(userName.equals(hu.getId().toString())){
								continue;
							}
						}
						reBuyone++;
					}
					if(i<45){
						//这里统计复购用户数
						if(StringUtils.isNotBlank(userName)){
							if(userName.equals(hu.getId().toString())){
								continue;
							}
						}
						reBuyTwo++;
					}
					if(i<60){
						//这里统计复购用户数
						if(StringUtils.isNotBlank(userName)){
							if(userName.equals(hu.getId().toString())){
								continue;
							}
						}
						reBuyThree++;
					}
				}
			}
		}
		
		/*
		//用户表中说有用户数量
		int buyOne =0;
		
		//七天里面的订单
		List<KllUserFormVo> oneList = userDataRepository.findOrderByWeek("30",source);
		for(KllUserFormVo vo:oneList){
			List<KllHupuUserVo> user = hupuUserRepository.findOrderByUid(vo.getId().toString());
			if(user !=null && user.size()>0){
				String userName = "";
				for(KllHupuUserVo hu:user){
					
					Date date = hu.getPayTime();
					int i = DateUtil.intervalDays(new Date(), date);
					if(i>=37){
						break;
					}else if(i<37 && i>=30){
						//分母
						if(StringUtils.isNotBlank(userName)){
							if(userName.equals(hu.getId().toString())){
								continue;
							}
						}
						buyOne++;
					}else if(i<30){
						//这里统计复购用户数
						if(StringUtils.isNotBlank(userName)){
							if(userName.equals(hu.getId().toString())){
								continue;
							}
						}
						reBuyone++;
					}
					userName = hu.getId().toString();
					
				}
			}
		}
		
		//45天复购率
		int buyTwo =0;
		int reBuyTwo =0;
		List<KllUserFormVo> twoList = userDataRepository.findOrderByWeek("45",source);
		for(KllUserFormVo vo:twoList){
			List<KllHupuUserVo> user = hupuUserRepository.findOrderByUid(vo.getId().toString());
			if(user !=null && user.size()>0){
				String userName = "";
				for(KllHupuUserVo hu:user){
					Date date = hu.getPayTime();
					int i = DateUtil.intervalDays(new Date(), date);
					if(i>=52){
						break;
					}else if(i<52 && i>=45){
						//分母
						if(StringUtils.isNotBlank(userName)){
							if(userName.equals(hu.getId().toString())){
								continue;
							}
						}
						buyTwo++;
					}else if(i<45){
						//这里统计复购用户数
						if(StringUtils.isNotBlank(userName)){
							if(userName.equals(hu.getId().toString())){
								continue;
							}
						}
						reBuyTwo++;
					}
				}
			}
		}
			
		
		//60天复购率
		int buyThree =0;
		int reBuyThree=0;
		List<KllUserFormVo> threeList = userDataRepository.findOrderByWeek("60",source);
		for(KllUserFormVo vo:threeList){
			List<KllHupuUserVo> user = hupuUserRepository.findOrderByUid(vo.getId().toString());
			if(user !=null && user.size()>0){
				String userName = "";
				for(KllHupuUserVo hu:user){
					Date date = hu.getPayTime();
					int i = DateUtil.intervalDays(new Date(), date);
					if(i>=67){
						break;
					}else if(i<67 && i>=60){
						//分母
						if(StringUtils.isNotBlank(userName)){
							if(userName.equals(hu.getId().toString())){
								continue;
							}
						}
						buyThree++;
					}else if(i<60){
						//这里统计复购用户数
						if(StringUtils.isNotBlank(userName)){
							if(userName.equals(hu.getId().toString())){
								continue;
							}
						}
						reBuyThree++;
					}
				}
			}
		}
		*/
		
		
		
		//新用户数
		//今日新增的用户数
		int weekCnt=0;
		List<KllHupuUserVo> hupuToday = hupuUserRepository.findUserByWeek(source);
		int index =0;//hupu当天实际新增用户
		int payCnt=0;//hupu当天实际新增用户 里面付款的用户
		for(KllHupuUserVo vo :hupuToday){
			List<KllUserFormVo> list = userDataRepository.deleteUserByOther(vo.getHupuUid(),"week");
			if(list != null && list.size()>0){
				
			}else{
				index ++;
				if(vo.getPayTime() != null){
					payCnt ++;
				}
			}
		}
		List<KllUserFormVo> kaluliToday = userDataRepository.findUserByKaluliWeek(source);
		if(hupuToday != null && hupuToday.size()>0){
			weekCnt += index;
		}
		if(kaluliToday != null && kaluliToday.size()>0){
			weekCnt += kaluliToday.get(0).getCount();
		}
		
		
		BigDecimal fourProp = new BigDecimal(0);
		BigDecimal threeProp = new BigDecimal(0);
		BigDecimal twoProp = new BigDecimal(0);
		BigDecimal oneProp = new BigDecimal(0);
		BigDecimal buyFournum = new BigDecimal(buyFour);
		if(buyFour ==0){
			
		}else{
			
			BigDecimal reBuyFournum = new BigDecimal(reBuyFour);
			fourProp = reBuyFournum.divide(buyFournum, 2, BigDecimal.ROUND_HALF_UP);
			
			//
			BigDecimal reBuyThreenum = new BigDecimal(reBuyThree);
			threeProp = reBuyThreenum.divide(buyFournum, 2, BigDecimal.ROUND_HALF_UP);
			//
			BigDecimal reBuyTwonum = new BigDecimal(reBuyTwo);
			twoProp = reBuyTwonum.divide(buyFournum, 2, BigDecimal.ROUND_HALF_UP);
			
			//
			BigDecimal reBuyonenum = new BigDecimal(reBuyone);
			oneProp = reBuyonenum.divide(buyFournum, 2, BigDecimal.ROUND_HALF_UP);
		}
		
		
		
		Map map = new HashMap<>();
		map.put("date",DateUtil.OneWeekStr()+"-"+DateUtil.getCurrentDay());
		map.put("oneProp",oneProp);
		map.put("twoProp",twoProp);
		map.put("threeProp",threeProp);
		map.put("fourProp",fourProp);
		map.put("weekCnt",weekCnt);
		
		return map;
	}
	
	
	

}
